import httpRequest from "./httpRequest";
import { findByType } from '@/api/sys/dict'

let dicts = [];
let dictTypes = {};

//从local中获取当前已有的列表
var sessionDicts_ = window.sessionStorage.getItem("dicts");
if (sessionDicts_ != null && sessionDicts_ != "") {
  //console.log('sessionDicts_' , sessionDicts_)
  try {
    dicts = JSON.parse(sessionDicts_);
  } catch (error) {
    dicts = [];
  }
}

var sessionDictTypes_ = window.sessionStorage.getItem("dictTypes");
if (sessionDictTypes_ != null && sessionDictTypes_ != "") {
  try {
    dictTypes = JSON.parse(sessionDictTypes_);
  } catch (error) {
    dictTypes = {};
  }
}

/**
 * dict 数据字典根据类型和值翻译为名称
 * @param {dictType} dictType
 * @param {dictValue} dictValue
 */
export function getDictName(dictType, dictValue) {
  // 尝试 获取
  let name = getDict(dictType, dictValue);

  return name;
}

export function putDict(dictType, name, value) {
  // console.log('dicts  q1 ' , dicts)
  dicts.push({ dictType: dictType, value: value, name: name });
  const json_ = JSON.stringify(dicts);
  window.sessionStorage.setItem("dicts", json_);
  //console.log('dicts2 ' , dicts)
}

function getDict(dictType, value) {
  // console.log('dicts' , dicts)
  if (dicts != null && dicts.length > 0) {
    for (var i in dicts) {
      if (dicts[i].value == value && dicts[i].dictType == dictType) {
        return dicts[i].name;
      }
    }
  }

  return null;
}

export function putDictType(dictType, value) {
  dictTypes[dictType] = value;

  const json_ = JSON.stringify(dictTypes);
  window.sessionStorage.setItem("dictTypes", json_);
}

export function getDictType(dictType) {
  const value = dictTypes[dictType];

  return value;
}

/**
 * 根据数据字典分类返回该分类下数据
 */
export function getDictTypeValues(dictType) {
  return new Promise((resolve, reject) => {
    // 判断缓存是否有数据
    const value = getDictType(dictType);
    if (value) {
      resolve(value);
    } else {
    
      findByType(dictType).then(({ data }) => {
          if (data.code === 0) {
            putDictType(dictType, data.data);

            resolve(data.data);
          }
        })
        .error(() => {
          reject();
        });
    }
  });
}

export function clearAll() {
  dicts = [];
  dictTypes = {};
  const json_1 = JSON.stringify(dicts)
  window.sessionStorage.setItem('dicts' , json_1);

  const json_2 = JSON.stringify(dictTypes)
  window.sessionStorage.setItem('dictTypes' , json_2);
} 